<?php
//包含数据库配置文件
define("BASEPATH","");
define("ENVIRONMENT","");
class AliexpressAuth {
    private $host="";
    private $name="";
    private $pass="";
    private $database="";
    private $link = "";
    private $table="d_shop";
    //protected $url = "http://wjdrkd.f3322.net:14580"; //公网回调地址
   // protected $url = "http://wjdrkd.f3322.net:14580/fuman/aliexpress/AliexpressAuth.php"; //公网回调地址
    protected $url = ""; //公网回调地址
    protected $urlApi = "http://gw.api.alibaba.com/openapi/param2/1/aliexpress.open/";
    public function __construct()
    {
        require_once(dirname(__FILE__).'/../../application/config/database.php');
        require_once(dirname(__FILE__).'/../../application/config/webset.php');
        $this->host = $db['default']['hostname'];
        $this->name = $db['default']['username'];
        $this->pass = $db['default']['password'];
        $this->database = $db['default']['database'];
        $this->url = $config['get_callback_url'];
        $this->connect();
    }
    //数据库的链接
     public function connect(){
         $this->link = mysqli_connect($this->host,$this->name,$this->pass) or die ($this->error());
          mysqli_select_db($this->link,$this->database) or die("没该数据库：".$this->database);
     }

    public function updToken($code,$id)
    {
        //获取code并插入或更新数据库操作
        $url = $this->url;
        //$code = $this->input->get('code'); //获取的code
        if(!$code){
            echo json_encode(array('code'=>1,'msg'=>'参数错误'));exit;
        }
        //$key = $this->input->get('state');
        //判断该code是否在数据库存在，存在更新freshtoken，否则insert
        $sql = "SELECT * FROM d_shop WHERE id = '$id' ";
        $rs  = mysqli_query($this->link,$sql);
        $rs  = mysqli_fetch_array($rs,MYSQLI_ASSOC);
        if($rs['appkey']&&$rs['appsecret']){
            $appkey = $rs['appkey'];
            $appsecret = $rs['appsecret'];
        }else{
            mysqli_close($this->link);
            echo json_encode(array('code'=>3,'msg'=>'参数错误'));exit;
        }
        //新店铺第一次获取code后，通过该参数获取相关token
        $result = $this->getToken($code,$appkey,$appsecret,$url);
        if(!empty($result['refresh_token'])){
            if($result['refresh_token']==$rs['refresh_token']){
                $data['access_token'] = $result['access_token'];
                $data['access_timeout'] = $result['expires_in']+time();
                $upd_sql = "UPDATE d_shop SET access_token = '{$data['access_token']}',access_timeout = '{$data['access_timeout']}' WHERE id = $id ";
            }else{
                $data['refresh_token'] = $result['refresh_token'];
                $data['access_token'] = $result['access_token'];
                $data['refresh_timeout'] = $result['refresh_token_timeout'];
                $data['access_timeout'] = $result['expires_in']+time();
                $upd_sql = "UPDATE d_shop SET refresh_token = '{$data['refresh_token']}',access_token = '{$data['access_token']}',refresh_timeout = '{$data['refresh_timeout']}',access_timeout = '{$data['access_timeout']}' WHERE id = $id ";
            }
            //执行sql语句
             mysqli_query($this->link,$upd_sql);
            //$this->db->where('appkey',$appkey);
            //$this->db->update('d_shop',$data);
            mysqli_close($this->link);
            return true;
            //return "http://wjdrkd.f3322.net:14580/management/setshop?platformID=10&other=";
           // header("http://wjdrkd.f3322.net:14580/management/setshop?platformID=10&other=");
        }else{
            mysqli_close($this->link);
            echo json_encode(array('code'=>4,'msg'=>'code is wrong'));exit;
        }

    }
    /*
    * 通过code获取accesstoken和refreshtoken
    */
    protected function getToken($code,$appKey,$appSecret){
        #根据code获取refresh_token、access_token
        #拼接获取token的Url
        $getTokenUrl='https://gw.api.alibaba.com/openapi/http/1/system.oauth2/getToken/'.$appKey;
        $data='grant_type=authorization_code&need_refresh_token=true&client_id='.$appKey.'&client_secret='.$appSecret.'&redirect_uri='.$this->url.'&code='.$code;
        $result = $this->sendCurlPostRequest($getTokenUrl,$data);
        return $result;
    }
    /*
    * 通过refreshToken换取accessToken
    */
    protected function getAccessToken($refreshtoken,$appkey,$appsecret)
    {
        $code_arr = array(
            'client_id' => $appkey,
            'grant_type' => 'refresh_token',
            'client_secret' => $appsecret,
            'refresh_token' => $refreshtoken,
        );
        //$sign_str = 'param2/1/system.oauth2/refreshToken/544880';
        //$code_sign = $this->getSign();
        $getTokenUrl = 'https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/getToken/'.$appkey;
        //$data = 'grant_type=refresh_token&refresh_token='.$refreshtoken.'&client_id='.$appkey.'&client_secret='.$appsecret.'&_aop_signature='.$code_sign;
        //此处不需要签名  注：此接口必须使用POST方法提交；必须使用https
        $data = 'grant_type=refresh_token&client_id='.$appkey.'&client_secret='.$appsecret.'&refresh_token='.$refreshtoken;
        $result = $this->sendCurlPostRequest($getTokenUrl,$data);
        return $result;
    }
    /*
    * 半年期限，剩余30天之内可以使用postponeToken接口换取新的refresh_token
     * 若调用该接口则之前使用refresh_token失效，新获取的refresh_token生效
    */
    protected function getRefreshToken($refreshtoken,$access_token,$appkey,$appsecret)
    {
        $code_arr = array(
            'client_id' => $appkey,
            'grant_type' => 'refresh_token',
            'client_secret' => $appsecret,
            'refresh_token' => $refreshtoken,
        );
        //$sign_str = 'param2/1/system.oauth2/refreshToken/544880';
        //$code_sign = $this->getSign();
        $getTokenUrl = 'https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/postponeToken/'.$appkey;
        //此处不需要签名  注：此接口可以使用Get或POST方法提交；必须使用https
        $data = 'client_id='.$appkey.'&client_secret='.$appsecret.'&refresh_token='.$refreshtoken.'&access_token='.$access_token;
        $result = $this->sendCurlPostRequest($getTokenUrl,$data);
        //返回数组类型的数据格式
       // {"aliId":"8888888888","resource_owner":"xxx","memberId":"xxxxxxx","expires_in":"36000","refresh_token":"479f9564-1049-456e-ab62-29d3e82277d9","access_token":"f14da3b8-b0b1-4f73-a5de-9bed637e0188","refresh_token_timeout":"20121222222222+0800"}
        return $result;
    }
    /**
     * 发送请求
     * @param  $url
     * @param $post_data
     */
    protected function sendCurlPostRequest($url,$post_data)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch,CURLOPT_POST,TRUE);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
        curl_setopt($ch,CURLOPT_TIMEOUT,300);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $response = curl_exec($ch);
        curl_close($ch);
        $response = json_decode($response,TRUE);
        return $response;
    }
    //模拟get请求
    protected function sendCurlGetRequest($url){
        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //是否抓取跳转后页面
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        $output = curl_exec($ch);
        curl_close($ch);
        $output= json_decode($output,1);
        return $output;

    }



}

/**
 * 实例化并操作
 *
 */
$code = isset($_GET['code']) ? trim($_GET['code']) : "";
$id   = isset($_GET['state']) ? trim($_GET['state']) : "";
if(!$code){
    echo json_encode(array('code'=>1,'msg'=>'参数错误'));exit;
}
if(!$id){
    echo json_encode(array('code'=>2,'msg'=>'参数错误'));exit;
}
if(get_magic_quotes_gpc()){
    //$code = addslashes($code);
     //$id = addslashes($id);
}else{
    $code = addslashes($code);
    $id = addslashes($id);
}

$obj_aliexpress = new AliexpressAuth();
//var_dump($db['default']);exit;
$rs = $obj_aliexpress->updToken($code,$id); //boolean 值
//授权成功跳转页面
header("Location:http://192.168.1.66/management/setshop?platformID=10&other=");exit;




?>